package com.heima.behavior.service.impl;

import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApUnlikeBehaviorService;
import com.heima.model.behavior.dtos.UnlikeBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUnlikeBehaviorService implements IApUnlikeBehaviorService {

    @Autowired
    private IApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * APP 端-文章详情页-用户对文章的喜欢或不喜欢行为
     * @param unlikeBehaviorDTO
     * @return
     */
    @Override
    public ResponseResult handleUnlike(UnlikeBehaviorDTO unlikeBehaviorDTO) {
        //1.校验参数
            //1.1校验登陆状态
        Integer loginId = AppThreadLocalUtils.getUser();
        if(loginId == null || loginId.intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
            //1.2获取用户的行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(loginId, null);
        if(apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "获取用户的行为实体失败");
        }
            //1.3接口幂等
        Query query = Query.query(Criteria.where("entry_id").is(apBehaviorEntry.getId()).and("article_id").is(unlikeBehaviorDTO.getArticleId()));
        ApUnlikesBehavior apUnlikesBehavior = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        if(apUnlikesBehavior != null && unlikeBehaviorDTO.getType().intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "文章已设置为不喜欢，请勿重复设置");
        }
        //2.处理喜欢或不喜欢行为
        if(unlikeBehaviorDTO.getType().intValue() == 0){
            //2.1处理喜欢
            apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            apUnlikesBehavior.setArticleId(unlikeBehaviorDTO.getArticleId());
            apUnlikesBehavior.setType(unlikeBehaviorDTO.getType());
            apUnlikesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(apUnlikesBehavior);
        }else{
            //2.2处理不喜欢，将 document 直接删除
            mongoTemplate.remove(query,ApUnlikesBehavior.class);
        }
        //3.返回响应
        return ResponseResult.okResult();
    }
}
